// 创建选中文本时显示的翻译按钮
let translateButton = document.createElement('div');
translateButton.style.cssText = `
    position: fixed;
    padding: 5px 10px;
    background: #4CAF50;
    color: white;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    z-index: 10000;
    display: none;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
`;
translateButton.textContent = '翻译选中文本';
document.body.appendChild(translateButton);

// 监听选中文本事件
document.addEventListener('mouseup', function(e) {
    const selectedText = window.getSelection().toString().trim();
    
    if (selectedText) {
        const selection = window.getSelection();
        const range = selection.getRangeAt(0);
        const rect = range.getBoundingClientRect();
        
        translateButton.style.left = `${rect.left + window.scrollX}px`;
        translateButton.style.top = `${rect.bottom + window.scrollY + 5}px`;
        translateButton.style.display = 'block';
        
        // 存储选中的文本
        translateButton.dataset.text = selectedText;
    } else {
        translateButton.style.display = 'none';
    }
});

// 点击其他地方时隐藏按钮
document.addEventListener('mousedown', function(e) {
    if (e.target !== translateButton) {
        translateButton.style.display = 'none';
    }
});

// 点击翻译按钮时发送消息给后台脚本
translateButton.addEventListener('click', function() {
    const text = this.dataset.text;
    if (text) {
        chrome.runtime.sendMessage({
            action: 'translate',
            text: text
        });
    }
}); 